package com.davidk.survey.server.user;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import com.davidk.survey.server.data.BaseDAO;
import com.davidk.survey.server.data.DataStoreException;
import com.davidk.survey.server.data.EMF;
import com.davidk.survey.server.data.UserAlreadyExistException;

public class UserDAO extends BaseDAO<User> {

	public UserDAO() {
		super(User.class.getName());
	}

	public static User sanitize(User user) {
		String pwMask = "";
		for (int i = 0; i < user.getPassword().length(); i++)
			pwMask += "*";
		user.setPassword(pwMask);
		return user;
	}

	@SuppressWarnings("unchecked")
	public static User getByName(String name) {

		EntityManager em = EMF.get().createEntityManager();
		List<User> users;
		try {
			javax.persistence.Query query = em.createQuery("select p from " + User.class.getName()
					+ " p where p.name='" + name + "'");
			users = (List<User>) query.getResultList();
			if (users.size() > 0)
				return sanitize(users.get(0));
		} catch (PersistenceException pex) {
			pex.printStackTrace(System.out);
		} finally {
			em.close();
		}
		return null;
	}

	public static void createUser(User user) throws UserAlreadyExistException, DataStoreException {
		User ret = getByName(user.getName());
		if (ret != null)
			throw new UserAlreadyExistException();
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.persist(user);
			sanitize(user);
		} catch (Exception ex) {
			System.err.println("createUser error : ");
			ex.printStackTrace(System.err);
			throw new DataStoreException(ex);
		} finally {
			em.close();
		}
	}

	public static void saveUser(User user) throws DataStoreException {
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.merge(user);
			sanitize(user);
		} catch (Exception ex) {
			System.err.println("saveUser error : ");
			ex.printStackTrace(System.err);
			throw new DataStoreException(ex);
		} finally {
			em.close();
		}
	}
}
